<?php
/**
 * Created by zengwei.
 * Date: 2019/10/10
 * Time: 16:13
 * Function:
 */

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Http\Requests\Api\AddCafeTagsRequest;
use App\Http\Requests\Api\CreateCafeRequest;
use App\Models\Cafe;
use App\Models\CafesPhoto;
use App\Models\Tag;
use App\Models\User;
use App\Utilities\GaodeMaps;
use App\Utilities\Tagger;

class CafeController extends Controller
{

    public function __construct()
    {

    }

    /**
     * Created by zengwei.
     * Date: 2019/10/15
     * Time: 10:15
     * Function:列表
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function index()
    {
        $cafes = (new Cafe())
            ->with(['brewMethods','company'])
            ->with(['tags'=>function($builder){
                $builder->select('name');
            }])
            ->withCount(['likes'])
            ->paginate();
        return response()->json(successDataFormat($cafes->items()));
    }

    /**
     * Created by zengwei.
     * Date: 2019/10/15
     * Time: 10:15
     * Function:添加
     * @param CreateCafeRequest $request
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function store(CreateCafeRequest $request)
    {
        $user = \Auth::guard('api')->user();
        $cafes = [];
        $parentId = 0;
        $locations = $request->input('locations');
        $name = $request->input('name');
        $website = $request->input('website');
        $description = $request->input('description')?:'';
        $roaster = $request->input('roaster')?1:0;
        $addedId = $user->id;
        \DB::beginTransaction();
        try{
            foreach($locations as $key=>$location){
                //获取经纬度
                $positionInfo = GaodeMaps::geocodeAddress($location['state'],$location['city'],$location['address']);
                if(is_null($positionInfo['lat']) || is_null($positionInfo['lng'])){
                    \DB::rollBack();
                    return response()->json(['message'=>'地址信息不准确'],400);
                }
                $cafe = new Cafe([
                    'parent_id'=>$parentId,
                    'name'=>$name,
                    'location_name'=>$location['name']?:'',
                    'website'=>$website,
                    'description'=>$description,
                    'roaster'=>$roaster,
                    'added_by'=>$addedId,
                    'address'=>$location['address'],
                    'city'=>$location['city'],
                    'state'=>$location['state'],
                    'zip'=>$location['zip'],
                    'latitude'=>$positionInfo['lat'],
                    'longitude'=>$positionInfo['lng'],
                ]);
                $cafe->save();
                //关联冲泡方法
                $brewMethods = $location['methodsAvailable'];
                $cafe->brewMethods()->sync($brewMethods);
                //添加标签
                $tags = $location['tags'];
                Tagger::tagCafe($cafe,$tags,$addedId);

                if($key == 0){
                    $parentId = $cafe->id;
                }
                $cafes[] = $cafe;
            }

            $photo = $request->file('photos');
            if($photo&&$photo->isValid()){
                $photoRes = $this->uploadImg($photo);
                if($photoRes['code']){
                    \DB::rollBack();
                    return response()->json(['message'=>$photoRes['msg']],400);
                }
                if($parentId){
                    $cafePhoto = new CafesPhoto();
                    $cafePhoto->cafe_id = $parentId;
                    $cafePhoto->uploaded_by = $user->id;
                    $cafePhoto->url = $photoRes['data']['path'];
                    $cafePhoto->save();
                }
            }
            \DB::commit();
            return response()->json(successDataFormat($cafes),201);
        }catch (\Exception $e){
            \DB::rollBack();
            return response()->json(['message'=>$e->getMessage()],400);
        }
    }

    /**
     * Created by zengwei.
     * Date: 2019/10/15
     * Time: 10:20
     * Function:详情
     * @param Cafe $cafe
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function show(Cafe $cafe)
    {
        $user = \Auth::guard('api')->user();
        $cafe->load(['brewMethods','tags','company']);
        $cafe->loadCount(['likes']);
        $cafe->user_liked = false;
        if($user&&$cafe->likes()->where('users.id',$user->id)->count()){
            $cafe->user_liked = true;
        }
        return response()->json(successDataFormat($cafe));
    }

    /**
     * Created by zengwei.
     * Date: 2019/10/15
     * Time: 16:08
     * Function:喜欢
     * @param Cafe $cafe
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function like(Cafe $cafe){

        $user = \Auth::guard('api')->user();
        $cafe->likes()->attach($user->id);
        return response()->json(successDataFormat(),201);
    }

    /**
     * Created by zengwei.
     * Date: 2019/10/15
     * Time: 16:08
     * Function:取消喜欢
     * @param Cafe $cafe
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function delLike(Cafe $cafe){
        //$user = User::select(['id','name'])->first();
        $user = \Auth::guard('api')->user();
        $cafe->likes()->detach($user->id);
        return response()->json(successDataFormat(),204);
    }

    /**
     * Created by zengwei.
     * Date: 2019/10/16
     * Time: 11:03
     * Function:添加标签
     * @param Cafe $cafe
     * @param AddCafeTagsRequest $request
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function addTags(Cafe $cafe,AddCafeTagsRequest $request){
        $user = \Auth::guard('api')->user();
        $tags = $request->input('tags');
        Tagger::tagCafe($cafe,$tags,$user->id);
        $cafe->load(['cafe']);
        return response()->json(successDataFormat($cafe),201);
    }

    /**
     * Created by zengwei.
     * Date: 2019/10/16
     * Time: 11:03
     * Function:删除标签
     * @param Cafe $cafe
     * @param Tag $tag
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function delTag(Cafe $cafe,Tag $tag){
        $user = \Auth::guard('api')->user();
        \DB::table('cafes_users_tags')
            ->where('cafe_id',$cafe->id)
            ->where('tag_id',$tag->id)
            ->where('user_id',$user->id)
            ->delete();
        return response()->json(successDataFormat(),204);
    }


    protected function uploadImg($img){
        try{
            $path = $img->store('public/cafephotos');
            $realPath = ltrim($path,'public');
            $realPath = 'storage'.$realPath;
            $url = env('APP_URL').$realPath;
            return successDataFormat(['path'=>$realPath,'url'=>$url]);
        }catch (\Exception $e){
            return failDataFormat('',$e->getMessage());
        }

    }

}
